package com.xafc.demo.security.service;

import cn.hutool.extra.spring.SpringUtil;
import com.xafc.demo.security.entity.UserDetailEntity;
import com.xafc.demo.sys.model.dto.MenuDto;
import com.xafc.demo.sys.model.entity.User;
import com.xafc.demo.sys.service.IUserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.AuthorityUtils;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.util.List;
import java.util.stream.Collectors;

/**
 * @Author: ZhangMing
 * @Date: 2021/4/15 13:49
 */
@Service
public class UserDetailServiceImpl implements UserDetailsService {

    @Autowired
    private IUserService userService;

    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        User user = userService.getUserByUsername(username);
        if(user == null){
            return null;
        }

        // 获取用户的权限
        Integer userId = user.getId();
        List<MenuDto> permDtoList = userService.getUserPerm(userId);
        List<String> userPermList = permDtoList.stream()
                .filter(m -> !StringUtils.isEmpty(m.getCode()))
                .map(m -> m.getCode().toUpperCase())
                .collect(Collectors.toList());
        List<GrantedAuthority>  authorities = AuthorityUtils
                .commaSeparatedStringToAuthorityList(String.join(",", userPermList));
        // 设置用户信息
        UserDetailEntity userDetailEntity = new UserDetailEntity(user.getUsername(), user.getPassword(), authorities);
        userDetailEntity.setId(user.getId());
        userDetailEntity.setSalt(user.getSalt());
        userDetailEntity.setStatus(user.getStatus());
        return userDetailEntity;
    }
}
